package org.apache.ibatis.binding;

import org.apache.ibatis.lang.UsesJava7;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * JDK动态代理的方式
 * 这个是代理类MapperProxy
 * 代理类需要实现InvocationHandler的invoke方法
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {

    private static final long serialVersionUID = -6424540398559729838L;
    private final SqlSession sqlSession;    //指定一个SqlSession
    private final Class<T> mapperInterface; //使用JDK动态代理的时候，代理类所需要的Mapper的接口定义
    private final Map<Method, MapperMethod> methodCache;

    /**
     * 代理类的构造方法
     * @param sqlSession      sqlSession
     * @param mapperInterface Mapper的接口定义
     * @param methodCache     将方法和MapperMethod进行缓存所存放的集合Map
     */
    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    /**
     * 实现InvocationHandler的invoke方法
     * @param proxy  代理对象
     * @param method 被调用的方法
     * @param args   方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            //method.getDeclaringClass()===> Returns the {@code Class} object representing the class or
            //interface that declares the method represented by this {@code Method} object.
            if (Object.class.equals(method.getDeclaringClass())) { //判断是否是一个类对象
                return method.invoke(this, args); //执行方法的调用
            } else if (isDefaultMethod(method)) {
                return invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
        //如果不是类，也就是一个映射器接口，就会生成MapperMethod对象，它是通过cachedMapperMethod方法对其进行初始化的，然后执行execute方法
        //把sqlSession和当前运行的参数进行传递进去
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }

    /**
     * 将映射器的方法进行缓存
     * @param method 执行的方法
     * @return
     */
    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) { //判断是否methodCache中已经存在该method，如果不存在则进行cache
            mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }

    @UsesJava7
    private Object invokeDefaultMethod(Object proxy, Method method, Object[] args) throws Throwable {
        final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        final Class<?> declaringClass = method.getDeclaringClass();
        return constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE).unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
    }

    /**
     * Backport of java.lang.reflect.Method#isDefault()
     */
    private boolean isDefaultMethod(Method method) {
        return ((method.getModifiers()
                & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
                && method.getDeclaringClass().isInterface();
    }
}
